<template>
  <div class="login">
    <div class="login-img"></div>
    <h1 class="login-title">觉灵文化管理平台</h1>
    <div class="content">
      <h3 class="form-title">登录</h3>
      <el-form @submit.native.prevent :model="form" :rules="rules" ref="form" class="demo-ruleForm">
        <el-form-item prop="userName">

          <div class="input-icon">
            <el-input type="text" v-model="form.userName" placeholder="请输入账号">
              <template slot="prepend">
                <i class="fa fa-user"></i>
              </template>
            </el-input>

          </div>
        </el-form-item>
        <el-form-item prop="password">

          <div class="input-icon">
            <el-input type="password" v-model="form.password" placeholder="请输入密码">
              <template slot="prepend">
                <i class="fa fa-lock"></i>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item prop="code">

          <div class="input-icon">
            <el-input type="text" v-model="form.code" maxlength="4" placeholder="请输入验证码">
              <template slot="append">
                <img @click="getVerCode" class="ver-code" :src="imgURL" alt="">
              </template>
            </el-input>

          </div>
        </el-form-item>

      </el-form>

      <div class="form-actions">
        <el-checkbox v-model="checked" style="margin-top:10px;">记住我</el-checkbox>
        <el-button type="primary" class="btn green pull-right" @click="getLogin" @keyup.enter.native="getLogin">登 录</el-button>
        <!-- <el-button :loading="isLoading" type="primary" class="btn green pull-right" @click="getLogin" @keyup.enter.native="getLogin">登 录</el-button> -->
      </div>
    </div>
  </div>
</template>
<script>
import indexPasswordReset from './indexPasswordReset'
export default {
  name: 'login',
  data () {
    var validateCode = (rule, value, callback) => {
      // console.log(value)
      if (!value) {
        return callback(new Error('请输入验证码'))
      }
      this.verCodeBlur().then(res => {
        // console.log(res)
        if (res.code === 200) {
          callback()
        } else {
          return callback(new Error(res.msg))
        }
      })
    }
    var validateUserName = (rule, value, callback) => {
      // console.log('账号', value)
      if (!value) {
        // console.log('账号err')
        return callback(new Error('请输入账号'))
      } else {
        // console.log('账号success')
        callback()
      }
    }
    var validatePassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {
      form: {
        code: '',
        userName: '',
        password: ''
      },
      dialogVisibleReset: false,
      passwordVisable: false,
      userId: '',
      userName: '',
      password: '',
      checked: false, // 记住我的复选框勾选状态属性
      isLoading: false, // 按钮添加loading动画的属性,
      imgURL: '', // 验证码图片地址 base64
      verification: '', // 验证码
      rules: {
        userName: [{ validator: validateUserName, trigger: 'blur' }],
        password: [{ validator: validatePassword, trigger: 'blur' }],
        code: [{ validator: validateCode, trigger: 'blur' }]
      }
    }
  },
  components: {
    indexPasswordReset
  },
  created () {
    // 获取登录信息的cookie
    this.getCookie()
    // 按键监听
    var _self = this
    var key = ''
    this.getVerCode()
    document.onkeydown = function (e) {
      if (window.event == undefined) {
        key = e.keyCode
      } else {
        key = window.event.keyCode
      }
      if (key == 13) {
        _self.getLogin()
        // _self.getLoginss()
      }
    }
  },
  methods: {
    // getLoginss () {
    //   alert(111)
    // },
    editPasswrd () {
      this.$alert('这是一段内容', '标题名称', {
        confirmButtonText: '确定',
        callback: action => {}
      })
    },
    getLogin () {
      var params = {
        // userName: this.userName,
        userName: this.form.userName,
        password: this.form.password,
        key: this.$store.state.user.codeKey,
        code: this.form.code
      }
      if (params.userName == '' || params.password == '') {
        this.$message({
          message: '请输入登录信息',
          type: 'warning',
          center: true
        })
        return false
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('user/Login', params).then(res => {
            console.log(res)
            if (res.code == 200) {
              this.userId = res.data.userId
              // 判断是否勾选了记住登录
                if (this.checked == true) {
                  // 目前固定为7天，可以自己修改
                  this.setCookie(params.userName, params.password, 7)
                } else if (this.checked == false) {
                  this.clearCookie()
                }
                localStorage.setItem('name', res.data.name)
                localStorage.setItem('phone', res.data.phone)
                localStorage.setItem('userName', params.userName)
                localStorage.setItem('userId', res.data.userId)
                // 在请求成功后把document.onkeydown置为undefined
                document.onkeydown = undefined
                this.$router.push('/index/home')
            } else {
              this.getVerCode() // 登陆失败刷新验证码
              // this.isLoading = false
              this.tip(res.msg, 'error')
            }
          })
        } else {
          // console.log('error submit!!')
          return false
        }
      })
      // this.isLoading = true
    },
    // 设置cookie
    setCookie (user, pwd, saveDays) {
      var exdate = new Date() // 获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * saveDays) // 保存的天数
      // 字符串拼接cookie
      window.document.cookie =
        'userName' + '=' + user + ';path=/;expires=' + exdate.toGMTString()
      // window.document.cookie = 'password' + '=' + pwd + ';path=/;expires=' + exdate.toGMTString()
    },
    // 读取cookie
    getCookie () {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split('; ') // 这里显示的格式需要切割一下自己可输出看下
        // console.log(arr)
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split('=') // 再次切割
          // 判断查找相对应的值
          if (arr2[0] == 'userName') {
            //  console.log(arr2[1])
            this.form.userName = arr2[1] // 保存到用户账号的地方
            this.checked = true
          }
        }
        // this.checked = true
      }
    },
    // 清除cookie
    clearCookie () {
      this.setCookie('', '', -1) // 登录信息改成空，天数改为-1
    },
    // 获取验证码
    getVerCode () {
      const key = this.$store.state.user.codeKey
      this.$store.dispatch('user/GetVerification', key).then(res => {
        console.log(res)
        if (res.code === 200) {
          console.log(this.$refs)
          this.$refs['form'].clearValidate('code')
          this.imgURL = 'data:image/jpg;base64,' + res.data.img
          console.log(this.imgUrl)
          this.$store.commit('user/SET_CODE_KEY', res.data.key)
        }
      })
    },
    verCodeBlur () {
      const params = {
        code: this.form.code,
        key: this.$store.state.user.codeKey
      }
      return this.$store
        .dispatch('user/CheckVerification', params)
        .then(res => {
          // console.log(res)
          if (res.code === 200) {
            return res
          } else {
            return res
          }
        })
    },
    // 关闭弹窗
    closeDialog (params, type) {
      console.log(params, type)
      if (params == 'reset') {
        this.dialogVisibleReset = false
      }
      // this.$store.dispatch('user/Logout').then(res => {
      //   // console.log(res)
      //   if (res.code == 200) {
      //     this.$store.commit('common/CLEAR_TAG')
      //   } else {
      //     // this.tip(res.msg, 'error')
      //   }
      // })
    },
    // 确认
    confirmDialog (params) {
      if (params == 'reset') {
        this.dialogVisibleReset = false
      }
      setTimeout(() => {
        this.$router.push('/index/home')
      }, 2000)
    }
  }
}
</script>
<style scoped lang="scss">
@import url('./css/bootstrap.min.css');
@import url('./css/login.css');
.login {
  .display-hide,
  .control-label {
    display: none;
  }
  .input-icon {
    position: relative;
    // margin-bottom: 16px;
  }
  .input-icon i {
    color: #ccc;
    z-index: 3;
    width: 16px;
    font-size: 16px;
    text-align: center;
  }
}
.ver-code {
  width: 58px;
  height: 30px;
}
</style>
